﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoupdateClient.Client
{
    using System.Net;
    using System.Threading.Tasks;
    using DotNetty.Buffers;
    using DotNetty.Transport.Channels;
    using DotNetty.Handlers.Timeout;
    using DotNetty.Handlers.Logging;
    using AutoupdateClient.Mgr;

    public class ClientHandler : ChannelHandlerAdapter
    {
        private Client m_Client { set; get; } = null;

        public ClientHandler(Client client)
        {
            this.m_Client = client;
        }

        public override void ChannelActive(IChannelHandlerContext context)
        {
            Console.WriteLine("Active:" + context.GetHashCode());

            ClientMgr.getInstance().registe();

            base.ChannelActive(context);
        }

        public override Task ConnectAsync(IChannelHandlerContext context, EndPoint remoteAddress, EndPoint localAddress)
        {
            Console.WriteLine("Connect:" + context.GetHashCode());

            return base.ConnectAsync(context, remoteAddress, localAddress);
        }

        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var byteBuffer = message as IByteBuffer;

            if (byteBuffer != null)
            {
                string msg = byteBuffer.ToString(Encoding.UTF8);

               // Console.WriteLine("Received from server=>" + msg);

                PacketMgr.getInstance().ProcessPacket(msg);



            }
             base.ChannelRead(context, message);
        }

        public override void ChannelInactive(IChannelHandlerContext context)
        {
            this.m_Client.connectToServer();

            Console.WriteLine("Inactive:" + context.GetHashCode());
            base.ChannelInactive(context);
        }

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            base.ExceptionCaught(context, exception);
        }

        public override void UserEventTriggered(IChannelHandlerContext context, object evt)
        {

            if (evt is IdleStateEvent)
            {
                var eventState = evt as IdleStateEvent;

                if (eventState != null)
                {
                    switch (eventState.State)
                    {
                        case IdleState.ReaderIdle:
                            break;

                        case IdleState.WriterIdle:

                            ClientMgr.getInstance().heartbeat();

                            break;

                        case IdleState.AllIdle:
                            break;
                    }
                }
            }

            //base.UserEventTriggered(context, evt);
        }
    }
}
